<?php
/*******************************************************************************
*  Title: Help Desk Software HESK
*  Version: 2.2 from 9th June 2010
*  Author: Klemen Stirn
*  Website: http://www.hesk.com
********************************************************************************
*  COPYRIGHT AND TRADEMARK NOTICE
*  Copyright 2005-2010 Klemen Stirn. All Rights Reserved.
*  HESK is a registered trademark of Klemen Stirn.

*  The HESK may be used and modified free of charge by anyone
*  AS LONG AS COPYRIGHT NOTICES AND ALL THE COMMENTS REMAIN INTACT.
*  By using this code you agree to indemnify Klemen Stirn from any
*  liability that might arise from it's use.

*  Selling the code for this program, in part or full, without prior
*  written consent is expressly forbidden.

*  Using this code, in part or full, to create derivate work,
*  new scripts or products is expressly forbidden. Obtain permission
*  before redistributing this software over the Internet or in
*  any other medium. In all cases copyright and header must remain intact.
*  This Copyright is in full effect in any country that has International
*  Trade Agreements with the United States of America or
*  with the European Union.

*  Removing any of the copyright notices without purchasing a license
*  is expressly forbidden. To remove HESK copyright notice you must purchase
*  a license for this script. For more information on how to obtain
*  a license please visit the page below:
*  https://www.hesk.com/buy.php
*******************************************************************************/

define('IN_SCRIPT',1);
define('HESK_PATH','../');

/* Get all the required files and functions */
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/database.inc.php');

hesk_session_start();
hesk_dbConnect();
hesk_isLoggedIn();

/* Is Knowledgebase enabled? */
if (!$hesk_settings['kb_enable'])
{
	hesk_error($hesklang['kbdis']);
}

/* Any category ID set? */
$catid = isset($_GET['category']) ? intval($_GET['category']) : 1;
$artid = isset($_GET['article']) ? intval($_GET['article']) : 0;

//Is action set?
$action = isset($_REQUEST['a']) ? hesk_input($_REQUEST['a']) : '';

if (isset($_GET['search']))
{
	$query = hesk_input($_GET['search']);
}
else
{
	$query = 0;
}

$hesk_settings['kb_link'] = ($artid || $catid != 1 || $query) ? '<a href="knowledgebase_private.php" class="smaller">'.$hesklang['kb_text'].'</a>' : $hesklang['kb_text'];

if ($hesk_settings['kb_search'] && $query)
{
    hesk_kb_search($query);
}
elseif ($artid)
{
    $sql = 'SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_articles` WHERE `id`=\''.hesk_dbEscape($artid).'\' AND `type`!=\'2\' LIMIT 1';
    $result  = hesk_dbQuery($sql);
    $article = hesk_dbFetchAssoc($result) or hesk_error($hesklang['kb_art_id']);
    hesk_show_kb_article($artid);
}
elseif ($action == 'new_article')
{
    new_article();  
}
elseif ($action == 'edit_article')
{
    edit_article();
}
elseif ($action == 'save_article')
{
    save_article();
}
elseif ($action == 'remove_article')
{
    remove_article();
}
else
{
    hesk_show_kb_category($catid);
}

require_once(HESK_PATH . 'inc/footer.inc.php');
exit();


/*** START FUNCTIONS ***/

function hesk_kb_header($kb_link) {
	global $hesk_settings, $hesklang;

	/* Print admin navigation */
	require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');
        
	?>

	</td>
	</tr>
	<tr>
	<td>

	<table width="100%" border="0" cellspacing="0" cellpadding="3">
	<tr>
	<td valign="top">
	<span class="smaller"><a href="<?php echo $hesk_settings['hesk_url']; ?>/admin/admin_main.php" class="smaller"><?php echo $hesklang['main_page']; ?></a>
	&gt; <?php echo $kb_link; ?></span>
	</td>
	<?php
	if ($hesk_settings['kb_search'])
	{
		echo '
		<td style="text-align:right" valign="top" width="300">
	    <div style="display:inline;">
	        <form action="knowledgebase_private.php" method="get" style="display: inline; margin: 0;">
			<input type="text" name="search" size="20" />
			<input type="submit" value="'.$hesklang['search'].'" class="yellowbutton" onmouseover="hesk_btn(this,\'yellowbuttonover\');" onmouseout="hesk_btn(this,\'yellowbutton\');" />
			</form>
		</div>
		</td>
	    ';
	}
        hesk_handle_messages();
	?>
	</tr>
	</table>
            
	</td>
	</tr>
        <tr>
	<td><?php
} // END hesk_kb_header()


function hesk_kb_search($query) {
	global $hesk_settings, $hesklang;

    define('HESK_NO_ROBOTS',1);

	/* Print header */
	require_once(HESK_PATH . 'inc/header.admin.inc.php');
	hesk_kb_header($hesk_settings['kb_link']);

	$sql = 'SELECT t1.* FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_articles` AS t1 LEFT JOIN `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` AS t2 ON t1.`catid` = t2.`id`  WHERE t1.`type`!=\'2\' AND t2.`type`!=\'2\' AND MATCH(`subject`,`content`) AGAINST (\''.hesk_dbEscape($query).'\') LIMIT '.hesk_dbEscape($hesk_settings['kb_search_limit']);
	$res = hesk_dbQuery($sql);
    $num = hesk_dbNumRows($res);

    ?>
	<p>&raquo; <b><?php echo $hesklang['sr']; ?> (<?php echo $num; ?>)</b></p>

	<?php
	if ($num == 0)
	{
		echo '<p><i>'.$hesklang['nosr'].'</i></p>';
        hesk_show_kb_category(1,1);
	}
    else
    {
?>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
	<td width="7" height="7"><img src="../img/roundcornerslt.jpg" width="7" height="7" alt="" /></td>
	<td class="roundcornerstop"></td>
	<td><img src="../img/roundcornersrt.jpg" width="7" height="7" alt="" /></td>
</tr>
<tr>
	<td class="roundcornersleft">&nbsp;</td>
	<td>
		<div align="center">
        <table border="0" cellspacing="1" cellpadding="3" width="100%">
        <?php
			while ($article = hesk_dbFetchAssoc($res))
			{
	            $txt = strip_tags($article['content']);
	            if (strlen($txt) > $hesk_settings['kb_substrart'])
	            {
	            	$txt = substr(strip_tags($article['content']),0,$hesk_settings['kb_substrart']).'...';
	            }

	            if ($hesk_settings['kb_rating'])
	            {
	            	$alt = $article['rating'] ? sprintf($hesklang['kb_rated'], sprintf("%01.1f", $article['rating'])) : $hesklang['kb_not_rated'];
	                $rat = '<td width="1" valign="top"><img src="../img/star_'.(hesk_round_to_half($article['rating'])*10).'.png" width="85" height="16" alt="'.$alt.'" border="0" style="vertical-align:text-bottom" /></td>';
	            }
	            else
	            {
	            	$rat = '';
	            }

				echo '
				<tr>
				<td>
	                <table border="0" width="100%" cellspacing="0" cellpadding="1">
	                <tr>
	                <td width="1" valign="top"><img src="../img/article_text.png" width="16" height="16" border="0" alt="" style="vertical-align:middle" /></td>
	                <td valign="top"><a href="knowledgebase_private.php?article='.$article['id'].'">'.$article['subject'].'</a></td>
	                '.$rat.'
                    </tr>
	                </table>
	                <table border="0" width="100%" cellspacing="0" cellpadding="1">
	                <tr>
	                <td width="1" valign="top"><img src="../img/blank.gif" width="16" height="10" style="vertical-align:middle" alt="" /></td>
	                <td><span class="article_list">'.$txt.'</span></td>
                    </tr>
	                </table>

	            </td>
				</tr>';
			}
	?>
    	</table>
        </div>
	</td>
	<td class="roundcornersright">&nbsp;</td>
</tr>
<tr>
	<td><img src="../img/roundcornerslb.jpg" width="7" height="7" alt="" /></td>
	<td class="roundcornersbottom"></td>
	<td width="7" height="7"><img src="../img/roundcornersrb.jpg" width="7" height="7" alt="" /></td>
</tr>
</table>

    <p>&nbsp;<br />&lt;&lt; <a href="javascript:history.go(-1)"><?php echo $hesklang['back']; ?></a></p>
    <?php
    } // END else

} // END hesk_kb_search()


function hesk_show_kb_article($artid) {
	global $hesk_settings, $hesklang, $article;

	/* Print header */
    $hesk_settings['tmp_title'] = $article['subject'];
	require_once(HESK_PATH . 'inc/header.admin.inc.php');
	hesk_kb_header($hesk_settings['kb_link']);

	$sql = 'SELECT `name`,`type` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` WHERE `id`=\''.hesk_dbEscape($article['catid']).'\' LIMIT 1';
	$result   = hesk_dbQuery($sql);
    $category = hesk_dbFetchAssoc($result) or hesk_error($hesklang['kb_cat_inv']);

    echo '<h3>'.$article['subject'].'</h3>

    <fieldset>
	<legend>'.$hesklang['as'].'</legend>
    '. $article['content'];

    if (!empty($article['attachments']))
    {
		echo '<p><b>'.$hesklang['attachments'].':</b><br />';
		$att=explode(',',substr($article['attachments'], 0, -1));
		foreach ($att as $myatt)
        {
			list($att_id, $att_name) = explode('#', $myatt);
			echo '<img src="../img/clip.png" width="16" height="16" alt="'.$att_name.'" style="align:text-bottom" /> <a href="../download_attachment.php?kb_att='.$att_id.'" rel="nofollow">'.$att_name.'</a><br />';
		}
		echo '</p>';
    }

    echo '</fieldset>';

    if ($article['catid']==1)
    {
    	$link = 'knowledgebase_private.php';
    }
    else
    {
    	$link = 'knowledgebase_private.php?category='.$article['catid'];
    }
    ?>

    <fieldset>
    <legend><?php echo $hesklang['ad']; ?></legend>
	<table border="0">
    <tr>
    <td><?php echo $hesklang['aid']; ?>: </td>
    <td><?php echo $article['id']; ?></td>
    </tr>
    <tr>
    <td><?php echo $hesklang['category']; ?>: </td>
    <td><a href="<?php echo $link; ?>"><?php echo $category['name']; ?></a></td>
    </tr>
    <tr>
    <td><?php echo $hesklang['dta']; ?>: </td>
    <td><?php echo hesk_date($article['dt']); ?></td>
    </tr>
    <tr>
    <td><?php echo $hesklang['views']; ?>: </td>
    <td><?php echo (isset($_GET['rated']) ? $article['views'] : $article['views']+1); ?></td>
    </tr>
    </table>
    </fieldset>

    <p>&nbsp;<br />&lt;&lt; <a href="javascript:history.go(<?php echo isset($_GET['rated']) ? '-2' : '-1'; ?>)"><?php echo $hesklang['back']; ?></a></p>

    <?php
} // END hesk_show_kb_article()


function hesk_show_kb_category($catid, $is_search = 0) {
    global $hesk_settings, $hesklang;
    
    //set add_menu visibility
    if($catid == 1){
        $add_menu = 1;
    } else {
        $add_menu = 0;
    }
    
    if ($is_search == 0)
    {
        /* Print header */
        require_once(HESK_PATH . 'inc/header.admin.inc.php');
        hesk_kb_header($hesk_settings['kb_link']);
        if (($catid == 1) && ($_SESSION['isadmin']==0)){
            echo $hesklang['kb_iss'].' &nbsp;<br /><br />';
        }
        else
        {
            echo $hesklang['kb_is'].' &nbsp;<br /><br />';
        }
    }

    $sql = 'SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` WHERE `id`=\''.hesk_dbEscape($catid).'\' LIMIT 1';
    $res = hesk_dbQuery($sql);
    $thiscat = hesk_dbFetchAssoc($res) or hesk_error($hesklang['kb_cat_inv']);

    if ($thiscat['parent'])
    {
            $link = ($thiscat['parent'] == 1) ? 'knowledgebase_private.php' : 'knowledgebase_private.php?category='.$thiscat['parent'];
            echo '<span class="homepageh3">&raquo; '.$hesklang['kb_cat'].': '.$thiscat['name'].'</span>
                &nbsp;(<a href="javascript:history.go(-1)">'.$hesklang['back'].'</a>)
            ';
    }

    $sql = 'SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` WHERE `parent`=\''.hesk_dbEscape($catid).'\' AND `type`!=\'2\' ORDER BY `parent` ASC, `cat_order` ASC';
    $result = hesk_dbQuery($sql);
    if (hesk_dbNumRows($result) > 0)
    {
    ?>

		<p>&raquo; <b><?php echo $hesklang['kb_cat_sub']; ?>:</b></p>

        <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
                <td width="7" height="7"><img src="../img/roundcornerslt.jpg" width="7" height="7" alt="" /></td>
                <td class="roundcornerstop"></td>
                <td><img src="../img/roundcornersrt.jpg" width="7" height="7" alt="" /></td>
        </tr>
        <tr>
                <td class="roundcornersleft">&nbsp;</td>
                <td>

                        <table border="0" cellspacing="1" cellpadding="3" width="100%">

                        <?php
                        $per_col = $hesk_settings['kb_cols'];
                        $i = 1;

                        while ($cat = hesk_dbFetchAssoc($result))
                        {

                                if ($i == 1)
                            {
                                        echo '<tr>';
                            }

                    $private = ($cat['type'] == 1) ? ' *' : '';

                                echo '
                            <td width="50%" valign="top">
                                <table border="0">
                                <tr><td><img src="../img/folder.gif" width="20" height="20" alt="" style="vertical-align:middle" /><a href="knowledgebase_private.php?category='.$cat['id'].'">'.$cat['name'].'</a>'.$private.'</td></tr>
                                ';

                                /* Print two most popular articles */
                                if ($hesk_settings['kb_numshow'] && $cat['articles'])
                            {
                                $sql = 'SELECT `id`,`subject`,`type` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_articles` WHERE `catid`=\''.hesk_dbEscape($cat['id']).'\' AND `type`!=\'2\' ORDER BY `views` DESC, `art_order` ASC LIMIT '.hesk_dbEscape(($hesk_settings['kb_numshow']+1));
                                $res = hesk_dbQuery($sql);
                                $num = 1;
                                        while ($art = hesk_dbFetchAssoc($res))
                                        {
                                $private = ($art['type'] == 1) ? ' *' : '';
                                                echo '
                                    <tr>
                                    <td><img src="../img/article_text.png" width="16" height="16" border="0" alt="" style="vertical-align:middle" />
                                    <a href="knowledgebase_private.php?article='.$art['id'].'" class="article">'.$art['subject'].'</a>'.$private.'</td>
                                    </tr>';

                                    if ($num == $hesk_settings['kb_numshow'])
                                    {
                                        break;
                                    }
                                    else
                                    {
                                        $num++;
                                    }
                                        }
                                if (hesk_dbNumRows($res) > $hesk_settings['kb_numshow'])
                                {
                                        echo '<tr><td>&raquo; <a href="knowledgebase_private.php?category='.$cat['id'].'"><i>'.$hesklang['m'].'</i></a></td></tr>';
                                }
                            }

                                echo '
                                </table>
                            </td>
                                ';

                                if ($i == $per_col)
                            {
                                        echo '</tr>';
                                $i = 0;
                            }
                                $i++;
                        }
                        /* Finish the table if needed */
                        if ($i != 1)
                        {
                                for ($j=1;$j<=$per_col;$j++)
                            {
                                        echo '<td width="50%">&nbsp;</td>';
                                        if ($i == $per_col)
                                    {
                                                echo '</tr>';
                                        break;
                                    }
                                $i++;
                            }
                        }

                        ?>
                        </table>

                </td>
                <td class="roundcornersright">&nbsp;</td>
        </tr>
        <tr>
                <td><img src="../img/roundcornerslb.jpg" width="7" height="7" alt="" /></td>
                <td class="roundcornersbottom"></td>
                <td width="7" height="7"><img src="../img/roundcornersrb.jpg" width="7" height="7" alt="" /></td>
        </tr>
        </table>
        
	<?php
	} // END if NumRows > 0
	?>
        <p>&raquo; <b><?php echo $hesklang['ac']; ?></b></p>

        <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
                <td width="7" height="7"><img src="../img/roundcornerslt.jpg" width="7" height="7" alt="" /></td>
                <td class="roundcornerstop"></td>
                <td><img src="../img/roundcornersrt.jpg" width="7" height="7" alt="" /></td>
        </tr>
        <tr>
                <td class="roundcornersleft">&nbsp;</td>
                <td>

                <?php
                $sql = 'SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_articles` WHERE `catid`=\''.hesk_dbEscape($catid).'\' AND `type`!=\'2\' ORDER BY `art_order` ASC';
                $res = hesk_dbQuery($sql);
                if (hesk_dbNumRows($res) == 0)
                {
                        echo '<p><i>'.$hesklang['noac'].'</i></p>';
                }
                else
                {
                                echo '<div align="center"><table border="0" cellspacing="1" cellpadding="3" width="100%">';
                                while ($article = hesk_dbFetchAssoc($res))
                                {
                        $private = ($article['type'] == 1) ? ' *' : '';

                            $txt = strip_tags($article['content']);
                            if (strlen($txt) > $hesk_settings['kb_substrart'])
                            {
                                $txt = substr(strip_tags($article['content']),0,$hesk_settings['kb_substrart']).'...';
                            }

                                        echo '
                                        <tr>
                                        <td>
                                <table border="0" width="100%" cellspacing="0" cellpadding="1">
                                <tr>
                                <td width="1" valign="top"><img src="../img/article_text.png" width="16" height="16" border="0" alt="" style="vertical-align:middle" /></td>
                                <td valign="top"><a href="knowledgebase_private.php?article='.$article['id'].'">'.$article['subject'].'</a>'.$private.'</td>
                            </tr>
                                </table>
                                <table border="0" width="100%" cellspacing="0" cellpadding="1">
                                <tr>
                                <td width="1" valign="top"><img src="../img/blank.gif" width="16" height="10" style="vertical-align:middle" alt="" /></td>
                                <td><span class="article_list">'.$txt.'</span></td>
                            </tr>
                                </table>
                            </td>
                                        </tr>';
                                }
                            echo '</table></div>';
                }
                ?>

                </td>
                <td class="roundcornersright">&nbsp;</td>
        </tr>
        <tr>
                <td><img src="../img/roundcornerslb.jpg" width="7" height="7" alt="" /></td>
                <td class="roundcornersbottom"></td>
                <td width="7" height="7"><img src="../img/roundcornersrb.jpg" width="7" height="7" alt="" /></td>
        </tr>
        </table>
        
        <?php
        //Get the region
        $query = "SELECT `kota` FROM ".hesk_dbEscape($hesk_settings['db_pfix'])."kota WHERE `id_kota`=".hesk_dbEscape($_SESSION['region'])." LIMIT 1";
        $result = hesk_dbQuery($query);
        $result = hesk_dbFetchAssoc($result);
        if (!isset($_SESSION['kota'])) {$_SESSION['kota'] = $result['kota'];}
        //Show all of the doctor article
        $id = $_SESSION[id];
        $sql = 'SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_articles` WHERE `author`='.hesk_dbEscape($id).' ORDER BY `art_order` ASC';
        $result = hesk_dbQuery($sql);
        $num	= hesk_dbNumRows($result);

        if ($num == 0){}
        else
        {
        ?>
        <hr />
        <div align="center">
        <table border="0" width="100%" cellspacing="1" cellpadding="3" class="white">
            <h3 align="center"><?php echo $hesklang['your_articles']; ?></h3>
            <br />
            <tr>
                <th class="admin_white">&nbsp;</th>
		<th class="admin_white"><b><i><?php echo $hesklang['name']; ?></i></b></th>
		<th class="admin_white"><b><i><?php echo $hesklang['region']; ?></i></b></th>
		<th class="admin_white"><b><i><?php echo $hesklang['kb_subject']; ?></i></b></th>
		<th class="admin_white"><b><i><?php echo $hesklang['kb_type']; ?></i></b></th>
                <th class="admin_white"><b><i><?php echo $hesklang['views']; ?></i></b></th>
                <?php
                if ($hesk_settings['kb_rating'])
                {
                ?>
                <th class="admin_white"><b><i><?php echo $hesklang['rating'].' ('.$hesklang['votes'].')'; ?></i></b></th>
                <?php
                }
                ?>
                <th class="admin_white">&nbsp;</th>
            </tr>
    	<?php

            $i=1;
            $j=1;

            while ($article=hesk_dbFetchAssoc($result))
            {

                if (isset($_SESSION['artord']) && $article['id'] == $_SESSION['artord'])
                {
                    $color = 'admin_green';
                    unset($_SESSION['artord']);
                }
                else
                {
                    $color = $i ? 'admin_white' : 'admin_gray';
                }
                $i = $i ? 0 : 1;

        	switch ($article['type'])
                {
                    case '1':
                        $type = $hesklang['kb_private'];
                        break;
                    case '2':
                        $type = $hesklang['kb_draft'];
                        break;
                    default:
                        $type = $hesklang['kb_published'];
                }

                if ($hesk_settings['kb_rating'])
                {
                    $alt = $article['rating'] ? sprintf($hesklang['kb_rated'], sprintf("%01.1f", $article['rating'])) : $hesklang['kb_not_rated'];
                    $rat = '<td class="'.$color.'" style="white-space:nowrap;"><img src="../img/star_'.(hesk_round_to_half($article['rating'])*10).'.png" width="85" height="16" alt="'.$alt.'" title="'.$alt.'" border="0" style="vertical-align:text-bottom" /> ('.$article['votes'].')</td>';
                }
                else
                {
                    $rat = '';
                }

        	?>
                <tr>
                    <td class="<?php echo $color; ?>"><?php echo $j; ?>.</td>
                    <td class="<?php echo $color; ?>"><?php echo $_SESSION['name']; ?></td>
                    <td class="<?php echo $color; ?>"><?php echo $_SESSION['kota']; ?></td>
                    <td class="<?php echo $color; ?>"><?php echo $article['subject']; ?></td>
                    <td class="<?php echo $color; ?>"><?php echo $type; ?></td>
                    <td class="<?php echo $color; ?>"><?php echo $article['views']; ?></td>
                    <?php echo $rat; ?>
                    <td class="<?php echo $color; ?>" style="text-align:center; white-space:nowrap;">
                        <a href="knowledgebase_private.php?a=edit_article&amp;id=<?php echo $article['id']; ?>"><img src="../img/edit.png" width="16" height="16" alt="<?php echo $hesklang['edit']; ?>" title="<?php echo $hesklang['edit']; ?>" border="0" /></a>
                        <a href="knowledgebase_private.php?a=remove_article&amp;id=<?php echo $article['id']; ?>&amp;token=<?php hesk_token_echo(); ?>" onclick="return hesk_confirmExecute('<?php echo $hesklang['del_art']; ?>');"><img src="../img/delete.png" width="16" height="16" alt="<?php echo $hesklang['delete']; ?>" title="<?php echo $hesklang['delete']; ?>" border="0" /></a>&nbsp;
                    </td>
                </tr>
            <?php
                $j++;
            } // End while
            ?>
        </table>
        </div>
        <?php
        }//End doctorarticle
        ?>
        
        <?php
        //hide this form for admin usage and category view
        if (($_SESSION['isadmin']==0) && ($add_menu == 1))
        {
            /* This person can't manage the knowledgebase, but can add it */
            /* Get Knowledgebase structure */
            $sql = 'SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` ORDER BY `parent` ASC, `cat_order` ASC';
            $result = hesk_dbQuery($sql);
            $kb_cat = array();

            while ($cat = hesk_dbFetchAssoc($result))
            {
                    $kb_cat[] = $cat;
            }

            /* Translate main category "Knowledgebase" if needed */
            $kb_cat[0]['name'] = $hesklang['kb_text'];

            require(HESK_PATH . 'inc/TreeMenu.php');
            $icon         = 'folder.gif';
            $expandedIcon = 'folder-expanded.gif';
            $menu		  = new HTML_TreeMenu();

            $thislevel = array('0');
            $nextlevel = array();
            $i = 1;
            $j = 1;

            if (isset($_SESSION['KB_CATEGORY']))
            {
                    $selected_catid = intval($_SESSION['KB_CATEGORY']);
            }
            else
            {
                    $selected_catid = 0;
            }

            while (count($kb_cat) > 0)
            {

                foreach ($kb_cat as $k=>$cat)
                {

                    if (in_array($cat['parent'],$thislevel))
                    {

                                    $up = $cat['parent'];
                                    $my = $cat['id'];
                                    $type = $cat['type'] ? '*' : '';
                                    $selected = ($selected_catid == $my) ? 1 : 0;

                        $text = str_replace('\\','\\\\',$cat['name']).$type.' ('.$cat['articles'].') [ '                  /* ' */
                                    .'<a href="#new_article" onclick="document.getElementById(\'option'.$j.'\').selected=true;return true;">'.$hesklang['kb_p_art'].'</a> | '
                                .'<a href="#new_category" onclick="document.getElementById(\'option'.$j.'_2\').selected=true;return true;">'.$hesklang['kb_p_cat'].'</a> | '
                                .'<a href="manage_knowledgebase.php?a=manage_cat&catid='.$my.'">'.$hesklang['kb_p_man'].'</a> ]';
                        $text_short = $cat['name'].$type.' ('.$cat['articles'].')';

                        if (isset($node[$up]))
                        {
                                $node[$my] = &$node[$up]->addItem(new HTML_TreeNode(array('hesk_selected' => $selected, 'text' => $text, 'text_short' => $text_short, 'hesk_catid' => $cat['id'], 'hesk_select' => 'option'.$j, 'icon' => $icon, 'expandedIcon' => $expandedIcon, 'expanded' => true)));
                        }
                        else
                        {
                            $node[$my] = new HTML_TreeNode(array('hesk_selected' => $selected, 'text' => $text, 'text_short' => $text_short, 'hesk_catid' => $cat['id'], 'hesk_select' => 'option'.$j, 'icon' => $icon, 'expandedIcon' => $expandedIcon, 'expanded' => true));
                        }

                            $nextlevel[] = $cat['id'];
                        $j++;
                            unset($kb_cat[$k]);

                    }

                }

                $thislevel = $nextlevel;
                $nextlevel = array();

                /* Break after 20 recursions to avoid hang-ups in case of any problems */
                if ($i > 20)
                {
                    break;
                }
                $i++;
            }

            $menu->addItem($node[1]);

            // Create the presentation class
            $treeMenu = & ref_new(new HTML_TreeMenu_DHTML($menu, array('images' => '../img', 'defaultClass' => 'treeMenuDefault', 'isDynamic' => true)));
            $listBox  = & ref_new(new HTML_TreeMenu_Listbox($menu));
        ?>
            <hr />
            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                            <td width="7" height="7"><img src="../img/roundcornerslt.jpg" width="7" height="7" alt="" /></td>
                            <td class="roundcornerstop"></td>
                            <td><img src="../img/roundcornersrt.jpg" width="7" height="7" alt="" /></td>
                    </tr>
                    <tr>
                    <td class="roundcornersleft">&nbsp;</td>
                    <td>

                        <div align="center">
                        <table border="0">
                        <tr>
                        <td>

                        <form action="knowledgebase_private.php" method="post" name="form1" enctype="multipart/form-data">

                            <h3 align="center"><?php echo $hesklang['new_kb_art']; ?></h3>
                        <br />

                            <table border="0">
                            <tr>
                            <td><b><?php echo $hesklang['kb_cat']; ?>:</b></td>
                            <td><select name="catid"><?php $listBox->printMenu(); ?></select></td>
                            </tr>
                            <input type="hidden" name="type" value="2"/>
                            <tr>
                            <td><b><?php echo $hesklang['kb_subject']; ?>:</b></td>
                            <td><input type="text" name="subject" size="70" maxlength="255" <?php if (isset($_SESSION['new_article']['subject'])) {echo 'value="'.$_SESSION['new_article']['subject'].'"';} ?> /></td>
                            </tr>
                            </table>

                    <div>
                            <p><b><?php echo $hesklang['kb_content']; ?>:</b><br />
                    <label><input type="radio" name="html" value="0" <?php if (!isset($_SESSION['new_article']['html']) || (isset($_SESSION['new_article']['html']) && $_SESSION['new_article']['html'] == 0) ) {echo 'checked="checked"';} ?> onclick="javascript:document.getElementById('kblinks').style.display = 'none'" /> <?php echo $hesklang['kb_dhtml']; ?></label><br />
                    <label><input type="radio" name="html" value="1" <?php $display = 'none'; if (isset($_SESSION['new_article']['html']) && $_SESSION['new_article']['html'] == 1) {echo 'checked="checked"'; $display = 'block';} ?> onclick="javascript:document.getElementById('kblinks').style.display = 'block'" /> <?php echo $hesklang['kb_ehtml']; ?></label><br />
                    <span id="kblinks" style="display:<?php echo $display; ?>"><i><?php echo $hesklang['kb_links']; ?></i><br /></span>
                    </div>

                            <textarea name="content" rows="25" cols="70"><?php if (isset($_SESSION['new_article']['content'])) {echo $_SESSION['new_article']['content'];} ?></textarea></p>

                            <p><b><?php echo $hesklang['attachments']; ?></b><br />
                    <input type="file" name="attachment[1]" size="50" /><br />
                    <input type="file" name="attachment[2]" size="50" /><br />
                    <input type="file" name="attachment[3]" size="50" /><br />
                            <?php echo$hesklang['accepted_types']; ?>: <?php echo '*'.implode(', *', $hesk_settings['attachments']['allowed_types']); ?><br />
                            <?php echo $hesklang['max_file_size']; ?>: <?php echo $hesk_settings['attachments']['max_size']; ?> Kb
                            (<?php echo sprintf("%01.2f",($hesk_settings['attachments']['max_size']/1024)); ?> Mb)
                            </p>

                            <p align="center"><input type="hidden" name="a" value="new_article" />
                    <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>" />
                    <input type="submit" value="<?php echo $hesklang['kb_save']; ?>" class="orangebutton" onmouseover="hesk_btn(this,'orangebuttonover');" onmouseout="hesk_btn(this,'orangebutton');" /></p>
                            </form>

                            </td>
                            </tr>
                            </table>
                        </div>
                    </td>
                    <td class="roundcornersright">&nbsp;</td>
                    </tr>
                    <tr>
                    <td><img src="../img/roundcornerslb.jpg" width="7" height="7" alt="" /></td>
                    <td class="roundcornersbottom"></td>
                    <td width="7" height="7"><img src="../img/roundcornersrb.jpg" width="7" height="7" alt="" /></td>
                    </tr>
            </table>
        <?php
        }
} // END hesk_show_kb_category()

function new_article() {
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check($_POST['token']);

	$_SESSION['hide'] = array(
		'treemenu' => 1,
		//'new_article' => 1,
		'new_category' => 1,
	);

    $hesk_error_buffer = '';

	$catid = hesk_isNumber($_POST['catid']) or $catid = 1;
    $type  = ($_POST['type'] == 1 || $_POST['type'] == 2) ? $_POST['type'] : 0;
    $html  = $_POST['html'] ? 1 : 0;
    $now   = hesk_date();

    $_SESSION['KB_CATEGORY'] = $catid;

    $subject = hesk_input($_POST['subject']) or $hesk_error_buffer .= '<li>' . $hesklang['kb_e_subj'] . '</li>';
    #$subject = hesk_input($_POST['subject'],$hesklang['kb_e_subj'],$_SERVER['PHP_SELF']);

    if ($html)
    {
	    if (empty($_POST['content']))
	    {
        	$hesk_error_buffer .= '<li>' . $hesklang['kb_e_cont'] . '</li>';
	    }

        $content = hesk_getHTML($_POST['content']);
    }
	else
    {
    	$content = hesk_input($_POST['content']) or $hesk_error_buffer .= '<li>' . $hesklang['kb_e_cont'] . '</li>';
	    $content = nl2br($content);
	    $content = hesk_makeURL($content);
    }

    /* Any errors? */
    if (strlen($hesk_error_buffer))
    {
		$_SESSION['new_article'] = array(
		'type' => $type,
		'html' => $html,
		'subject' => $subject,
		'content' => hesk_input($_POST['content']),
		);

    	$hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
    	hesk_process_messages($hesk_error_buffer,$_SERVER['PHP_SELF']);
    }

    $revision = sprintf($hesklang['revision1'],$now,$_SESSION['user'].' ('.$_SESSION['name'].')');

    /* Article attachments */
	define('KB',1);
    require_once(HESK_PATH . 'inc/attachments.inc.php');
    $attachments = array();
    for ($i=1;$i<=3;$i++)
    {
        $att = hesk_uploadFile($i);
        if (!empty($att))
        {
            $attachments[$i] = $att;
        }
    }
	$myattachments='';

	/* Add to database */
	if (!empty($attachments))
	{
	    foreach ($attachments as $myatt)
	    {
	        $sql = "INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_attachments` (`saved_name`,`real_name`,`size`) VALUES (
            '".hesk_dbEscape($myatt['saved_name'])."',
            '".hesk_dbEscape($myatt['real_name'])."',
            '".hesk_dbEscape($myatt['size'])."'
            )";
	        $result = hesk_dbQuery($sql);
	        $myattachments .= hesk_dbInsertID() . '#' . $myatt['real_name'] .',';
	    }
	}

	/* Get the latest reply_order */
	$sql = 'SELECT `art_order` FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_articles` WHERE `catid`='.hesk_dbEscape($catid).' ORDER BY `art_order` DESC LIMIT 1';
	$res = hesk_dbQuery($sql);
	$row = hesk_dbFetchRow($res);
	$my_order = $row[0]+10;

    /* Insert article into database */
	$sql = "INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` (`catid`,`dt`,`author`,`subject`,`content`,`type`,`html`,`art_order`,`history`,`attachments`) VALUES (
    '".hesk_dbEscape($catid)."',
    NOW(),
    '".hesk_dbEscape($_SESSION['id'])."',
    '".hesk_dbEscape($subject)."',
    '".hesk_dbEscape($content)."',
    '".hesk_dbEscape($type)."',
    '".hesk_dbEscape($html)."',
    '".hesk_dbEscape($my_order)."',
    '".hesk_dbEscape($revision)."',
    '".hesk_dbEscape($myattachments)."'
    )";
	$result = hesk_dbQuery($sql);

	/* Update category article count */
    if ($type == 0)
    {
	    $sql = 'UPDATE `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` SET `articles`=`articles`+1 WHERE `id`='.hesk_dbEscape($catid);
		$result = hesk_dbQuery($sql);
	}

    unset($_SESSION['hide']);
    unset($_SESSION['new_article']['content']);

    hesk_process_messages($hesklang['your_kb_added'],'knowledgebase_private.php','SUCCESS');
} // End new_article()

function edit_article() {
	global $hesk_settings, $hesklang;

    $id = hesk_isNumber($_GET['id'],$hesklang['kb_cat_inv']);

    /* Get article details */
	$sql = 'SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_articles` WHERE `id`='.hesk_dbEscape($id).' LIMIT 1';
	$result = hesk_dbQuery($sql);
    if (hesk_dbNumRows($result) != 1)
    {
    	hesk_error($hesklang['kb_art_id']);
    }
    $article = hesk_dbFetchAssoc($result);

    if ($article['html'])
    {
		$article['content'] = htmlspecialchars($article['content']);
    }
    else
    {
		$from = array('/\<a href="mailto\:([^"]*)"\>([^\<]*)\<\/a\>/i', '/\<a href="([^"]*)" target="_blank"\>([^\<]*)\<\/a\>/i');
		$to   = array("$1", "$1");
		$article['content'] = preg_replace($from,$to,$article['content']);
		$article['content'] = str_replace('<br />','',$article['content']);
    }

    $catid = $article['catid'];

    if (isset($_SESSION['edit_article']))
    {
    	$_SESSION['edit_article'] = hesk_stripArray($_SESSION['edit_article']);
	$article['html'] = $_SESSION['edit_article']['html'];
        $article['subject'] = $_SESSION['edit_article']['subject'];
        $article['content'] = $_SESSION['edit_article']['content'];
        $article['catid'] = $_SESSION['edit_article']['catid'];
    }

    /* Get categories */
	$sql = 'SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` ORDER BY `parent` ASC, `cat_order` ASC';
	$result = hesk_dbQuery($sql);
	$kb_cat = array();

	while ($cat = hesk_dbFetchAssoc($result))
	{
		$kb_cat[] = $cat;
        if ($cat['id'] == $article['catid'])
        {
        	$this_cat = $cat;
            $this_cat['parent'] = $article['catid'];
        }
	}

	/* Translate main category "Knowledgebase" if needed */
	$kb_cat[0]['name'] = $hesklang['kb_text'];

	require(HESK_PATH . 'inc/TreeMenu.php');
	$icon         = HESK_PATH . 'img/folder.gif';
	$expandedIcon = HESK_PATH . 'img/folder-expanded.gif';
    $menu		  = new HTML_TreeMenu();

	$thislevel = array('0');
	$nextlevel = array();
	$i = 1;
	$j = 1;

	while (count($kb_cat) > 0)
	{

	    foreach ($kb_cat as $k=>$cat)
	    {

	    	if (in_array($cat['parent'],$thislevel))
	        {

	        	$up = $cat['parent'];
	            $my = $cat['id'];
	            $type = $cat['type'] ? '*' : '';

	            $text_short = $cat['name'].$type.' ('.$cat['articles'].')';

	            if (isset($node[$up]))
	            {
		            $node[$my] = &$node[$up]->addItem(new HTML_TreeNode(array('hesk_parent' => $this_cat['parent'], 'text' => 'Text', 'text_short' => $text_short, 'hesk_catid' => $cat['id'], 'hesk_select' => 'option'.$j, 'icon' => $icon, 'expandedIcon' => $expandedIcon, 'expanded' => true)));
	            }
	            else
	            {
	                $node[$my] = new HTML_TreeNode(array('hesk_parent' => $this_cat['parent'], 'text' => 'Text',  'text_short' => $text_short, 'hesk_catid' => $cat['id'], 'hesk_select' => 'option'.$j, 'icon' => $icon, 'expandedIcon' => $expandedIcon, 'expanded' => true));
	            }

		        $nextlevel[] = $cat['id'];
	            $j++;
		        unset($kb_cat[$k]);

	        }

	    }

	    $thislevel = $nextlevel;
	    $nextlevel = array();

	    /* Break after 20 recursions to avoid hang-ups in case of any problems */

	    if ($i > 20)
	    {
	    	break;
	    }
	    $i++;
	}

	$menu->addItem($node[1]);

	// Create the presentation class
	$listBox  = & ref_new(new HTML_TreeMenu_Listbox($menu));

	/* Print header */
	require_once(HESK_PATH . 'inc/header.admin.inc.php');

	/* Print main manage users page */
	require_once(HESK_PATH . 'inc/show_admin_nav.inc.php');
	?>

	</td>
	</tr>
	<tr>
	<td>

	<p><span class="smaller"><a href="knowledgebase_private.php" class="smaller"><?php echo $hesklang['menu_kb']; ?></a> &gt;
        <?php echo $hesklang['kb_art_edit']; ?></span></p>

	<?php
	/* This will handle error, success and notice messages */
	hesk_handle_messages();
	?>

	<table width="100%" border="0" cellspacing="0" cellpadding="0">
	<tr>
		<td width="7" height="7"><img src="../img/roundcornerslt.jpg" width="7" height="7" alt="" /></td>
		<td class="roundcornerstop"></td>
		<td><img src="../img/roundcornersrt.jpg" width="7" height="7" alt="" /></td>
	</tr>
	<tr>
	<td class="roundcornersleft">&nbsp;</td>
	<td>

	    <div align="center">
	    <table border="0">
	    <tr>
	    <td>

		<h3 align="center"><?php echo $hesklang['kb_art_edit']; ?></h3>
        <br />

		<form action="knowledgebase_private.php" method="post" name="form1" enctype="multipart/form-data">

		<table border="0">
		<tr>
		<td><b><?php echo $hesklang['kb_cat']; ?>:</b></td>
		<td><select name="catid"><?php $listBox->printMenu()?></select></td>
		</tr>
		<input type="hidden" name="type" value="<?php echo $article['type']; ?>"/>
		<tr>
		<td><b><?php echo $hesklang['kb_subject']; ?>:</b></td>
		<td><input type="text" name="subject" size="70" maxlength="255" value="<?php echo $article['subject']; ?>" /></td>
		</tr>
		</table>

		<p><b><?php echo $hesklang['kb_content']; ?>:</b><br />
        <label><input type="radio" name="html" value="0" <?php if (!$article['html']) {echo 'checked="checked"';} ?> onclick="javascript:document.getElementById('kblinks').style.display = 'none'" /> <?php echo $hesklang['kb_dhtml']; ?></label><br />
        <label><input type="radio" name="html" value="1" <?php if ($article['html']) {echo 'checked="checked"';} ?> onclick="javascript:document.getElementById('kblinks').style.display = 'block'" /> <?php echo $hesklang['kb_ehtml']; ?></label><br />
        <span id="kblinks" style="display: <?php echo $article['html'] ? 'block' : 'none'  ?>"><i><?php echo $hesklang['kb_links']; ?></i><br /></span>
		<textarea name="content" rows="25" cols="70"><?php echo $article['content']; ?></textarea></p>

		<p><b><?php echo $hesklang['attachments']; ?>:</b><br />
        <?php
	    if (!empty($article['attachments']))
	    {
			$att=explode(',',substr($article['attachments'], 0, -1));
			foreach ($att as $myatt)
	        {
				list($att_id, $att_name) = explode('#', $myatt);
				echo '[<a href="manage_knowledgebase.php?a=remove_kb_att&amp;id='.$id.'&amp;kb_att='.$att_id.'&amp;token='.hesk_token_echo(0).'" onclick="return hesk_confirmExecute(\''.$hesklang['delatt'].'\');">'.$hesklang['remove'].'</a>] <img src="../img/clip.png" width="16" height="16" alt="'.$att_name.'" style="align:text-bottom" /> <a href="../download_attachment.php?kb_att='.$att_id.'" rel="nofollow">'.$att_name.'</a><br />';
			}
			echo '<br />';
	    }
        ?>

        <input type="file" name="attachment[1]" size="50" /><br />
        <input type="file" name="attachment[2]" size="50" /><br />
        <input type="file" name="attachment[3]" size="50" /><br />
		<?php echo$hesklang['accepted_types']; ?>: <?php echo '*'.implode(', *', $hesk_settings['attachments']['allowed_types']); ?><br />
		<?php echo $hesklang['max_file_size']; ?>: <?php echo $hesk_settings['attachments']['max_size']; ?> Kb
		(<?php echo sprintf("%01.2f",($hesk_settings['attachments']['max_size']/1024)); ?> Mb)
		</p>

		<p align="center"><input type="hidden" name="a" value="save_article" />
	    <input type="hidden" name="id" value="<?php echo $id; ?>" /><input type="hidden" name="old_type" value="<?php echo $article['type']; ?>" />
	    <input type="hidden" name="old_catid" value="<?php echo $catid; ?>" />
        <input type="hidden" name="token" value="<?php hesk_token_echo(); ?>" />
        <input type="submit" value="<?php echo $hesklang['kb_save']; ?>" class="orangebutton" onmouseover="hesk_btn(this,'orangebuttonover');" onmouseout="hesk_btn(this,'orangebutton');" /></p>
		</form>

		</td>
		</tr>
		</table>
	    </div>

	</td>
	<td class="roundcornersright">&nbsp;</td>
	</tr>
	<tr>
	<td><img src="../img/roundcornerslb.jpg" width="7" height="7" alt="" /></td>
	<td class="roundcornersbottom"></td>
	<td width="7" height="7"><img src="../img/roundcornersrb.jpg" width="7" height="7" alt="" /></td>
	</tr>
</table>

	    <br /><hr />

<table width="100%" border="0" cellspacing="0" cellpadding="0">
	<tr>
		<td width="7" height="7"><img src="../img/roundcornerslt.jpg" width="7" height="7" alt="" /></td>
		<td class="roundcornerstop"></td>
		<td><img src="../img/roundcornersrt.jpg" width="7" height="7" alt="" /></td>
	</tr>
	<tr>
	<td class="roundcornersleft">&nbsp;</td>
	<td>

    	<h3><?php echo $hesklang['revhist']; ?></h3>

		<ul><?php echo $article['history']; ?></ul>

	</td>
	<td class="roundcornersright">&nbsp;</td>
	</tr>
	<tr>
	<td><img src="../img/roundcornerslb.jpg" width="7" height="7" alt="" /></td>
	<td class="roundcornersbottom"></td>
	<td width="7" height="7"><img src="../img/roundcornersrb.jpg" width="7" height="7" alt="" /></td>
	</tr>
</table>

	<?php
    /* Clean unneeded session variables */
    hesk_cleanSessionVars('edit_article');


    require_once(HESK_PATH . 'inc/footer.inc.php');
    exit();
} // END edit_article()

function save_article() {
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check($_POST['token']);

    $hesk_error_buffer = '';

    $id    = hesk_isNumber($_POST['id'],$hesklang['kb_art_id']);
	$catid = hesk_isNumber($_POST['catid']) or $catid = 1;
    $type  = ($_POST['type'] == 1 || $_POST['type'] == 2) ? $_POST['type'] : 0;
    $html  = $_POST['html'] ? 1 : 0;
    $now   = hesk_date();
    $old_catid = hesk_isNumber($_POST['old_catid']);
    $old_type  = ($_POST['old_type'] == 1 || $_POST['old_type'] == 2) ? $_POST['old_type'] : 0;

    #$subject = hesk_input($_POST['subject'],$hesklang['kb_e_subj']);
    $subject = hesk_input($_POST['subject']) or $hesk_error_buffer .= '<li>' . $hesklang['kb_e_subj'] . '</li>';

    if ($html)
    {
	    if (empty($_POST['content']))
	    {
	    	$hesk_error_buffer .= '<li>' . $hesklang['kb_e_cont'] . '</li>';
	    }
        
	    $content = hesk_getHTML($_POST['content']);
    }
	else
    {
    	$content = hesk_input($_POST['content']) or $hesk_error_buffer .= '<li>' . $hesklang['kb_e_cont'] . '</li>';
	    $content = nl2br($content);
	    $content = hesk_makeURL($content);
    }

    /* Any errors? */
    if (strlen($hesk_error_buffer))
    {
		$_SESSION['edit_article'] = array(
		'type' => $type,
		'html' => $html,
		'subject' => $subject,
		'content' => hesk_input($_POST['content']),
        'catid' => $catid,
        'resetviews' => (isset($_POST['resetviews']) ? 'Y' : 0),
        'resetvotes' => (isset($_POST['resetvotes']) ? 'Y' : 0),
		);

    	$hesk_error_buffer = $hesklang['rfm'].'<br /><br /><ul>'.$hesk_error_buffer.'</ul>';
    	hesk_process_messages($hesk_error_buffer,'./knowledgebase_private.php');
    }

    $extra_sql = '';
    if (isset($_POST['resetviews']) && $_POST['resetviews']=='Y')
    {
    	$extra_sql .= ',`views`=0 ';
    }
    if (isset($_POST['resetvotes']) && $_POST['resetvotes']=='Y')
    {
    	$extra_sql .= ',`votes`=0, `rating`=0 ';
    }

    /* Article attachments */
	define('KB',1);
    require_once(HESK_PATH . 'inc/attachments.inc.php');
    $attachments = array();
    for ($i=1;$i<=3;$i++)
    {
        $att = hesk_uploadFile($i);
        if (!empty($att))
        {
            $attachments[$i] = $att;
        }
    }
	$myattachments='';

	/* Add to database */
	if (!empty($attachments))
	{
	    foreach ($attachments as $myatt)
	    {
	        $sql = "INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_attachments` (`saved_name`,`real_name`,`size`) VALUES ('".hesk_dbEscape($myatt['saved_name'])."', '".hesk_dbEscape($myatt['real_name'])."', '".hesk_dbEscape($myatt['size'])."')";
	        $result = hesk_dbQuery($sql);
	        $myattachments .= hesk_dbInsertID() . '#' . $myatt['real_name'] .',';
	    }

        $extra_sql .= ", `attachments` = CONCAT(`attachments`, '".$myattachments."') ";
	}

    /* Update article in the database */
    $revision = sprintf($hesklang['revision2'],$now,$_SESSION['name'].' ('.$_SESSION['user'].')');
	$sql = "UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_articles` SET
    `catid`=".hesk_dbEscape($catid).",
    `subject`='".hesk_dbEscape($subject)."',
    `content`='".hesk_dbEscape($content)."' $extra_sql ,
    `type`='".hesk_dbEscape($type)."',
    `html`='".hesk_dbEscape($html)."',
    `history`=CONCAT(`history`,'".hesk_dbEscape($revision)."')
    WHERE `id`=".hesk_dbEscape($id)." LIMIT 1";
    $result = hesk_dbQuery($sql);

	/* Update proper category article count */
    if ($type == $old_type)
    {
    	if ($type == 0 && ($catid != $old_catid))
        {
		    $sql = 'UPDATE `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` SET `articles`=`articles`+1 WHERE `id`='.hesk_dbEscape($catid);
			$result = hesk_dbQuery($sql);

		    $sql = 'UPDATE `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` SET `articles`=`articles`-1 WHERE `id`='.hesk_dbEscape($old_catid);
			$result = hesk_dbQuery($sql);
        }
    }
    else
    {
    	if ($old_type == 0)
        {
		    $sql = 'UPDATE `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` SET `articles`=`articles`-1 WHERE `id`='.hesk_dbEscape($old_catid);
            $result = hesk_dbQuery($sql);
        }
        else
        {
		    $sql = 'UPDATE `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` SET `articles`=`articles`+1 WHERE `id`='.hesk_dbEscape($catid);
            $result = hesk_dbQuery($sql);
        }
    }

    hesk_process_messages($hesklang['your_kb_mod'],'knowledgebase_private.php','SUCCESS');
} // END save_article()

function remove_article() {
	global $hesk_settings, $hesklang;

	/* A security check */
	hesk_token_check($_GET['token']);

	$id = hesk_isNumber($_GET['id'],$hesklang['kb_art_id']);

    /* Get article details */
	$sql = 'SELECT * FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_articles` WHERE `id`='.hesk_dbEscape($id).' LIMIT 1';
	$result = hesk_dbQuery($sql);

    if (hesk_dbNumRows($result) != 1)
    {
    	hesk_error($hesklang['kb_art_id']);
    }

    $article = hesk_dbFetchAssoc($result);
	$catid = $article['catid'];

    $sql = 'DELETE FROM `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_articles` WHERE `id`='.hesk_dbEscape($id).' LIMIT 1';
    $result = hesk_dbQuery($sql);

    /* Remove any attachments */
	if (!empty($article['attachments']))
	{
		$att=explode(',',substr($article['attachments'], 0, -1));
		foreach ($att as $myatt)
		{
			list($att_id, $att_name) = explode('#', $myatt);

			/* Get attachment info */
			$sql = "SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_attachments` WHERE `att_id`=".hesk_dbEscape($att_id)." LIMIT 1";
			$result = hesk_dbQuery($sql);
			if (hesk_dbNumRows($result) == 1)
			{
				$file = hesk_dbFetchAssoc($result);
                unlink('../attachments/'.$file['saved_name']);
			}
			$sql = "DELETE FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."kb_attachments` WHERE `att_id`=".hesk_dbEscape($att_id)." LIMIT 1";
			$result = hesk_dbQuery($sql);
		}
	}

    /* Update category article count */
    if ($article['type'] == 0)
	{
    	$sql = 'UPDATE `'.hesk_dbEscape($hesk_settings['db_pfix']).'kb_categories` SET `articles`=`articles`-1 WHERE `id`='.hesk_dbEscape($catid);
		$result = hesk_dbQuery($sql);
    }

	hesk_process_messages($hesklang['your_kb_deleted'],'knowledgebase_private.php','SUCCESS');
} // End remove_article()
?>
